package com.example.testgit.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.testgit.VO.*;
import com.example.testgit.entity.BedDO;
import com.example.testgit.entity.DormitoryDO;
import com.example.testgit.entity.DormitoryRewardDO;
import com.example.testgit.entity.StudentDO;
import com.example.testgit.mapper.BedMapper;
import com.example.testgit.mapper.DormitoryMapper;
import com.example.testgit.mapper.DormitoryRewardMapper;
import com.example.testgit.mapper.StudentMapper;
import com.example.testgit.mapstruct.BedConverter;
import com.example.testgit.mapstruct.DormitoryRewardConverter;
import com.example.testgit.mapstruct.DormitoryRoomieConverter;
import com.example.testgit.service.AcademyService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@Service
public class AcademyServiceImpl implements AcademyService {

    @Resource
    private DormitoryMapper dormitoryMapper;

    @Resource
    private DormitoryRewardMapper dormitoryRewardMapper;

    @Resource
    private StudentMapper studentMapper;
    @Resource
    private BedMapper bedMapper;
    @Override
    public  PageResult<DormitoryRewardVO> queryDormitoryReward(StudentQuery stu){

        QueryWrapper<DormitoryDO> wrapper = new QueryWrapper<>();
        wrapper.eq("stu_id",stu.getStuId());
        DormitoryDO dormitoryDO = dormitoryMapper.selectOne(wrapper);

        QueryWrapper<DormitoryRewardDO> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("dormitory_id", dormitoryDO.getDormitoryId());

        Page<DormitoryRewardDO> page = new Page<>(stu.getPageNum(), stu.getPageSize());
        Page<DormitoryRewardDO> dormitoryRewardDoPage = dormitoryRewardMapper.selectPage(page, wrapper1);
        PageResult pageResult = new PageResult(dormitoryRewardDoPage);
        pageResult.setData(DormitoryRewardConverter.INSTANCE.toVOList(dormitoryRewardDoPage.getRecords()));

        String dormitoryId = dormitoryDO.getDormitoryId();
        String[] split = dormitoryId.split("-");
        String dormitoryBuild = split[0];
        String dormitoryNumber = split[1];

        int rewardCount = 3;
        int warningCount = 1;

        JSONObject json = new JSONObject();
        json.put("dormitoryBuild", dormitoryBuild);
        json.put("dormitoryNumber", dormitoryNumber);
        json.put("rewardCount", rewardCount);
        json.put("warningCount", warningCount);
        pageResult.setNote(json);

        return pageResult;
    }

    @Override
    public List<DormitoryRoomieVO> queryRoomie(StudentQuery stu){

        QueryWrapper<DormitoryDO> wrapper = new QueryWrapper<>();
        wrapper.eq("stu_id",stu.getStuId());
        DormitoryDO dormitoryDO = dormitoryMapper.selectOne(wrapper);

        QueryWrapper<DormitoryDO> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("dormitory_id",dormitoryDO.getDormitoryId());
        List<DormitoryDO> dormitoryDO1 = dormitoryMapper.selectList(wrapper1);

        List<StudentDO> studentDO = new ArrayList<>();
        QueryWrapper<StudentDO> wrapperStu = new QueryWrapper<>();
        for(int i = 0; i < dormitoryDO1.size();i++){
            wrapperStu.clear();
            if(!stu.getStuId().equals(dormitoryDO1.get(i).getStuId())) {
                wrapperStu.eq("stu_id", dormitoryDO1.get(i).getStuId());
                studentDO.add(studentMapper.selectOne(wrapperStu));
            }
        }

        List<DormitoryRoomieVO> dormitoryRoomieVOList = DormitoryRoomieConverter.INSTANCE.toVOList(studentDO);

        for (DormitoryRoomieVO dormitoryRoomieVO : dormitoryRoomieVOList){
            dormitoryRoomieVO.setClassName(dormitoryRoomieVO.getMajor()+dormitoryRoomieVO.getClassNum());
        }

        return dormitoryRoomieVOList;
    }

    @Override
    public PageResult<BedVO> queryBed(StudentQuery stu){
        QueryWrapper<BedDO> wrapper = new QueryWrapper<>();
        wrapper.eq("stu_id",stu.getStuId());
        wrapper.lt("bed_type",2);
        List<BedDO> bedDOListedDO = bedMapper.selectList(wrapper);

        QueryWrapper<BedDO> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("stu_id",stu.getStuId());
        wrapper2.gt("bed_type",0);

        Page<BedDO> page = new Page<>(stu.getPageNum(), stu.getPageSize());
        Page<BedDO> bedDOPage = bedMapper.selectPage(page, wrapper2);

        PageResult pageResult = new PageResult(bedDOPage);
        pageResult.setData(BedConverter.INSTANCE.toVOList(bedDOPage.getRecords()));

        // 日期与归寝时间转化为分开的String格式
        DateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        for (BedVO bedVO : (List<BedVO>)pageResult.getData()){
            if (bedVO.getBedType().equals("晚归")) {
                String bedTime = sdf.format(bedVO.getDate());
                String[] split = bedTime.split(" ");
                String[] hours = split[1].split(":");
                String ss = String.valueOf(Integer.parseInt(hours[0]) + 16);
                String sTime = String.valueOf(new StringBuilder().append(ss).append(":").append(hours[1]).append(":").append(hours[2]));
                bedVO.setBedDate(split[0]);
                bedVO.setBedTime(sTime);
            }else {
                String bedTime = sdf.format(bedVO.getDate());
                String[] split = bedTime.split(" ");
                bedVO.setBedDate(split[0]);
                bedVO.setBedTime("--:--:--");
            }
        }

        // 学期平均归寝时间计算
        String[] timeArray = new String[180];
        // 取时间到timeArray数组
        int numCount;
        for(numCount = 0; numCount<bedDOListedDO.size(); numCount++){
            Timestamp ts = bedDOListedDO.get(numCount).getDate();
            String bedTime = ts.toString();
            String[] split = bedTime.split(" ");
            String[] hours = split[1].split(":");
            String ss = String.valueOf(Integer.parseInt(hours[0]) + 16);
            String sTime = String.valueOf(new StringBuilder().append(ss).append(":").append(hours[1]).append(":").append(hours[2]));
            timeArray[numCount] = sTime; // hours 少16
            System.out.println("测试" + timeArray[numCount]);
        }
        String newAverageTime = calculation(timeArray,numCount);

        // 学期晚归和未归次数
        List<BedDO> bedDOListedDO2 = bedMapper.selectList(wrapper2);
        int lateCount = 0;
        int notCount = 0;
        for (int i = 0; i < bedDOListedDO2.size(); i++){
            if(bedDOListedDO2.get(i).getBedType() == 1){
                lateCount++;
            }else if(bedDOListedDO2.get(i).getBedType() == 2){
                notCount++;
            }
        }

        JSONObject json = new JSONObject();
        json.put("newAverageTime", newAverageTime);
        json.put("lateCount", lateCount);
        json.put("notCount", notCount);
        pageResult.setNote(json);

        return pageResult;
    }

    @Override
    public List<PieVO> pie(Integer stuId){
        QueryWrapper<BedDO> wrapper = new QueryWrapper<>();
        wrapper.eq("stu_id",stuId);
        List<BedDO> bedDOListedDO = bedMapper.selectList(wrapper);
        List<PieVO> pieVOS = new ArrayList<>();

        String[] sss = {"正常归寝","晚归","未归"};
        int count[] = {0,0,0};
        for (int i = 0 ;i<3;i++) {
            PieVO pies = new PieVO();
            pies.setName(sss[i]);
            pies.setValue(count[i]);
            pieVOS.add(pies);
        }

        for (BedDO bedDO : bedDOListedDO){
            PieVO pies = new PieVO();
            if (bedDO.getBedType() == 0){
                count[0]++;
                pies.setName(sss[0]);
                pies.setValue(count[0]);
                pieVOS.set(0,pies);
            }
            if (bedDO.getBedType() == 1){
                count[1]++;
                pies.setName(sss[1]);
                pies.setValue(count[1]);
                pieVOS.set(1,pies);
            }
            if (bedDO.getBedType() == 2){
                count[2]++;
                pies.setName(sss[2]);
                pies.setValue(count[2]);
                pieVOS.set(2,pies);
            }
        }

        return pieVOS;
    }

    /**
     * 计算平均归寝时间
     */
    public static String calculation(String[] strArray,int len) {

        //总共秒数
        long total = 0;
        for (int i = 0; i < len; i++) {

            if(strArray[i] == null){
                break;
            }
            String time[] = strArray[i].toString().split(":"); //时分秒分割
            long l1 = Long.parseLong(time[0]) * 3600; //小时转为秒数
            long l2 = Long.parseLong(time[1]) * 60; //分钟转为秒数
            String[] sTime = time[2].split("\\.");
           // System.out.println("*********"+sTime[0]+"\\*****"+time[2]);
            long l3 = Long.parseLong(sTime[0]); //秒数
            total += (l1 + l2 + l3);
        }

        //平均秒数
        long average = total / len; //计算平均每天的秒数

        //平均时间大于24点，显示第二天的时间，并且减去第一天的时长
        String nextDay = "";
        if (average >= 24 * 3600) {
            average = average - (24 * 3600);
            nextDay = "第二天";
        }

        long average1 = average / 3600; //秒数转小时
        long average2 = (average % 3600) / 60; //秒数转分钟
        long average3 = (average % 3600) % 60; //秒

        //不足两位前面补0
        String d1 = addZero(average1);
        String d2 = addZero(average2);
        String d3 = addZero(average3);
        String showTime = d1 + ":" + d2 + ":" + d3; //拼接时分秒
        showTime = showTime.equals("24:00:00") ? "00:00:00" : showTime;
        return showTime;
    }

    /**
     * 日期时间补0
     */
    public static String addZero(long i) {
        return i < 10 ? ("0" + i) : i + "";
    }
}
